package treazy.ultimate.stats;

import java.util.ArrayList;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class ViewTournamentsActivity extends ListActivity {
	/** Called when the activity is first created. */
	private ArrayList<Tournament> tourneytList;
	private ArrayList<String> tourneyNames;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		ActionBar actionBar = getActionBar();
	    actionBar.setDisplayHomeAsUpEnabled(true);
		
		DatabaseHandler db = new DatabaseHandler(this);
		tourneytList = db.getTournaments();
		
		tourneyNames = new ArrayList<String>();
		
		if(tourneytList.isEmpty()) { 
			tourneyNames.add("No Tournaments");
		} else {
			for(Tournament t: tourneytList){
				tourneyNames.add(t.getName());
			}	
		}
		setListAdapter(new ArrayAdapter<String>(this, R.layout.viewtournaments, R.id.tournamentlist, tourneyNames));
		ListView listView = getListView();
		listView.setTextFilterEnabled(true);
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if(tourneyNames.get(0) != "No Tournaments") {
					
					// Go to ViewGamesActivity
					Object selectedTourney = parent.getItemAtPosition(position);
					Intent i = new Intent(getApplicationContext(), NewGameActivity.class);
					i.putExtra("TournamentName", selectedTourney.toString());
					startActivity(i);
				}
			}
		});
		
	}
	
	@Override 
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.tournamentsmenu, menu);
	    
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.addTourney:
	        	startActivity(new Intent(getApplicationContext(), NewGameActivity.class));
	            return true;
	        case android.R.id.home:
	        	Intent i = new Intent(getApplicationContext(), UltiSystemsActivity.class);
	        	i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	        	startActivity(i);
	        	return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
}
